package agent;

import java.util.Vector;

import com.CharNotValidException;
import com.Event;
import com.LedsManager;
import com.ParamsLabel;

/**
 * 
 * @author Francesco Aiello, Antonio Guerrieri, Raffaele Gravina
 *
 */
public class AgentProxy implements IAgentProxy {
	
	/**
	 * Migrant Agent's ID
	 */
	private String agentID;
	
	/**
	 * Migrant Agent's Destination Address 
	 */
	private String agentAddress;
	
	/**
	 * Migrant's Agent Events Queue 
	 */
	private Vector events;
	
	/**
	 * The constructor. Two parameters about Migrant Agent are needed 
	 * @param agentID Migrant Agent's ID
	 * @param agentAddress Migrant Agent's Destination Address
	 */
	public AgentProxy(String agentID, String agentAddress) {
		this.agentID = agentID;
		this.agentAddress = agentAddress;
		this.events = new Vector();
	}
	
	/**
	 * Adds an event to the Events Queue
	 * @param event Event to add
	 */
	public void addEvent(Event event) {
		/*
		 * set the destination address of the event
		 */
		this.setAddressToEvent(event);
		this.events.addElement(event);	
	}
	
	/**
	 * Getter of the property <tt>agentAddress</tt>
	 * 
	 * @return Returns the Agent Address
	 */
	public String getAgentAddress() {
		return this.agentAddress;
	}

	/**
	 * Getter of the property <tt>events</tt>
	 * 
	 * @return Returns the Events Queue
	 */
	public Vector getEvents() {
		return this.events;
	}
	
	/**
	 * Getter of the property <tt>agentID</tt>
	 * 
	 * @return Returns the Agent ID
	 */
	public String getAgentID() {
		return this.agentID;
	}

	/**
	 * Clears the Events Queue after a successful migration
	 */
	public void clearEvents() {
		events = null;
		Runtime.getRuntime().gc();
	}

	/**
	 * Check the Events Queue to tell if the migration is execetud or not. If
	 * the queue is null the migration is executed
	 * @return Returns if the migration is executed or not
	 */
	public boolean isMigrationExecuted() {
		return events == null;
	}
	
	/**
	 * Set the destination address to the event
	 * @param event event to set the address
	 */
	private void setAddressToEvent(Event event) {
		try {
			event.setParam(ParamsLabel.EVT_ADDRESS, this.agentAddress);
		}
		catch (CharNotValidException e) {
			LedsManager.error();
			e.printStackTrace();
		}
	}
	
}
